const mysql = require('mysql2/promise');
const pool = require('../config/db'); // 假设db.js配置了数据库连接池

// 获取所有商品
exports.getAll = async function getAll(callback) {
  try {
    const [rows] = await pool.query('SELECT id, name, price, description FROM products');
    callback(null, rows);
  } catch (error) {
    callback(error);
  }
};

// 添加商品
exports.add = async function add(product, callback) {
  // 确保产品结构至少包含id, name, price, description
  if (!product.name || !product.price || !product.description) {
    return callback({ error: '缺少必需的产品信息（name, price, description）' });
  }
  try {
    const [result] = await pool.query('INSERT INTO products (name, price, description) VALUES (?, ?, ?)', [product.name, product.price, product.description]);
    product.id = result.insertId;
    callback(null, product);
  } catch (error) {
    callback(error);
  }
};

// 根据ID获取商品详情
exports.getById = async function getById(id, callback) {
  try {
    const [rows] = await pool.query('SELECT * FROM products WHERE id = ?', [id]);
    if (rows.length === 0) {
      callback({ kind: 'not_found' }, null);
    } else {
      callback(null, rows[0]);
    }
  } catch (error) {
    callback(error);
  }
};

// 更新商品
exports.update = async function update(id, updates, callback) {
  try {
    await pool.query('UPDATE products SET ? WHERE id = ?', [updates, id]);
    callback(null, { id, ...updates }); // 假设更新成功，返回更新后的商品信息
  } catch (error) {
    callback(error);
  }
};

// 删除商品
exports.delete = async function deleteProduct(id, callback) {
  try {
    await pool.query('DELETE FROM products WHERE id = ?', [id]);
    callback(null);
  } catch (error) {
    callback(error);
  }
};